package com.jonluo.uploader.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jonluo.model.UploadFiles;
import com.jonluo.service.UploadFilesService;
import com.jonluo.uploader.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 *
 * 文件上传controller
 */
@Controller
@RequestMapping("/fileUploader")
public class FileUploadController {

    // 图片允许格式
    @Value("${file.upload.allow.photos}")
    private String photos;
    // 文件允许格式
    @Value("${file.upload.allow.files}")
    private String files;

    @Autowired
    StorageService storageService;
    @Autowired
    UploadFilesService uploadFilesService;
    /*
     * @GetMapping("/") public String listUploadedFiles(Model model) throws
     * IOException {
     * 
     * model.addAttribute("files", storageService .loadAll() .map(path ->
     * MvcUriComponentsBuilder .fromMethodName(FileUploadController.class,
     * "serveFile", path.getFileName().toString()) .build().toString())
     * .collect(Collectors.toList()));
     * 
     * return "uploadForm"; }
     */

    /**
     * 加载文件上传控件
     * @param request
     * @return
     */
    @RequestMapping("/index")
    public ResponseEntity<String> handleFileUpload(HttpServletRequest request) {
        File file =null;
        /**
         * 参数
         * type："file" 文件 "photo" 图片 默认为photo
         * more： 数字，最多上传多少个文件 ，默认为1
         * uploadAction： true 能上传 false不能上传,默认为false
         * filenames：文件名字符串，多个以；隔开
         * index：一个页面多个组件要设置
         */
        String type =request.getParameter("type");
        String more =request.getParameter("more");
        String index =request.getParameter("index");
        String action = request.getParameter("uploadAction");
        boolean uploadAction = Boolean.parseBoolean(action == null ? "false" :action);
        String filenames =request.getParameter("filenames");
        JSONObject json = (JSONObject) JSON.parse("{\"pathNames\":\""+filenames+"\"}");
        /*根据filename获取htmlFiles的内容*/
        List<UploadFiles> list = new ArrayList<UploadFiles>();
        String htmlFiles = "";
        if (filenames !=null && !"".equals(filenames)) {
            list = (List<UploadFiles>) ((Map<String, Object>) uploadFilesService.getAll(json).getBody()).get("data");
        }

        /**
         * html 替换内容
         */
        String htmlIndex = index == null ? "" : index;
        String htmlLimit = more == null ? "1" : more;
        String htmlType = "";
        if ("file".equals(type)){
            htmlType = files;
        }else {
            htmlType = photos;
        }
        String host = "http://"+request.getHeader("host");
        htmlFiles = htmlFiles+"[";
        for (int i = 0; i<list.size();i++){
            UploadFiles uploadFiles = list.get(i);
            if (i != 0){
                htmlFiles= htmlFiles +",";
            }
            htmlFiles= htmlFiles+"{name:'"+uploadFiles.getName()+"',"+
                    "size:"+uploadFiles.getSize()+","+
                    "type:'"+uploadFiles.getType()+"',"+
                    "file:'/doc/files/"+uploadFiles.getPathName()+"',"+
                    "size2:'"+uploadFiles.getSize2()+"',"+
                    "data:{url:'/doc/files/"+uploadFiles.getPathName()+"'," +
                    "downurl:'"+host+"/fileUploader/downloadFile/"+uploadFiles.getPathName()+"'," +
                    "title:'"+uploadFiles.getPathName()+"',"+
                    "uploaded: true}}";

        }
        htmlFiles = htmlFiles+"]";
        String htmlStype = "";
        if (!uploadAction){
            //隐藏删除按钮
            htmlStype = "style=\"display: none;\"";
        }

        String fileContent = "";
        try {
            file = ResourceUtils.getFile("classpath:index.html");
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                int line = 1;
                // 一次读入一行，直到读入null为文件结束
                String fileString = "";
                while ((fileString = reader.readLine()) != null) {
                    fileContent+=fileString;
                    line++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        /*替换html内容*/
       fileContent =  fileContent.replaceAll("@TYPE@",htmlType)
                   .replaceAll("@LIMIT@",htmlLimit)
                   .replaceAll("@FILES@",htmlFiles)
                   .replaceAll("@STYPE@",htmlStype)
                   .replaceAll("@INDEX@",htmlIndex);


        return ResponseEntity.ok(fileContent);
    }


    @RequestMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity.ok(file);
    }

    @RequestMapping("/downloadFile/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) throws UnsupportedEncodingException {
        JSONObject json = (JSONObject) JSON.parse("{\"pathNames\":\""+filename+";"+"\"}");
        Resource file = storageService.loadAsResource(filename);
        UploadFiles uf = ((List<UploadFiles>) ((Map<String, Object>) uploadFilesService.getAll(json).getBody()).get("data")).get(0);

       //  下载
       return ResponseEntity.ok()
                             .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" +
                                     new String(uf.getName().getBytes("gb2312"),"iso8859-1") + "\"")
                             .body(file);
    }

    @RequestMapping("/deleteFile/{filename:.+}")
    @ResponseBody
    public ResponseEntity<String> deleteFile(@PathVariable String filename) {
        //删除文件
        storageService.deleteByName(filename);
        //删除文件信息
        JSONObject json = (JSONObject) JSON.parse("{\"pathName\":\""+filename+"\"}");
        uploadFilesService.deleteByPathName(json);
        return ResponseEntity.ok("{\"msg\":\"success\"}");
    }

   @RequestMapping("/upload")
   @ResponseBody
    public Map<String,String> handleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

       String name = request.getParameter("name");
       String type = request.getParameter("type");
       String size2 = request.getParameter("size2");
       long size = Long.parseLong(request.getParameter("size"));
       //保存文件
       String fileName = storageService.store(file,"file");
       JSONObject json = new JSONObject();

       json.put("id", "file0000"+UUID.randomUUID().toString().replace("-",""));
       json.put("name",name);
       json.put("pathName",fileName);
       json.put("type", type);
       json.put("size2",size2);
       json.put("size",size);
       json.put("uploadDate",new Date());
       //保存文件信息数据
       int status = uploadFilesService.add(json).getStatusCode().value();
       String host = "http://"+request.getHeader("host");
       Map<String,String> map = new HashMap<String,String>();
       map.put("host",host);
       map.put("fileName",fileName);
        return map;
    }

    @ExceptionHandler(com.jonluo.uploader.exception.StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(com.jonluo.uploader.exception.StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }



}
